import { useEffect, useRef, memo, useId } from 'react'
import { useLanguage } from '../contexts/LanguageContext'

interface TradingViewWidgetProps {
  symbol: string
  theme?: 'light' | 'dark'
  height?: number | string
}

function TradingViewWidget({ symbol, theme = 'dark', height = 500 }: TradingViewWidgetProps) {
  const containerId = useId()
  const container = useRef<HTMLDivElement>(null)
  const { language } = useLanguage()

  useEffect(() => {
    if (!container.current) return

    // 清理容器
    container.current.innerHTML = ''

    const script = document.createElement('script')
    script.src = 'https://s3.tradingview.com/external-embedding/embed-widget-advanced-chart.js'
    script.type = 'text/javascript'
    script.async = true
    
    // 处理交易对格式
    // 移除可能的斜杠，例如 BTC/USDT -> BTCUSDT
    let cleanSymbol = symbol.replace('/', '').toUpperCase()
    // 如果没有后缀，默认添加 USDT
    if (!cleanSymbol.endsWith('USDT') && !cleanSymbol.endsWith('USD')) {
      cleanSymbol += 'USDT'
    }
    
    // 默认使用币安数据
    const tvSymbol = `BINANCE:${cleanSymbol}`

    script.innerHTML = JSON.stringify({
      autosize: true,
      symbol: tvSymbol,
      interval: '60', // 默认1小时
      timezone: 'Asia/Shanghai',
      theme: theme,
      style: '1', // 1 = K线图
      locale: language === 'zh' ? 'zh_CN' : 'en',
      enable_publishing: false,
      allow_symbol_change: true,
      calendar: false,
      support_host: 'https://www.tradingview.com',
      hide_side_toolbar: false,
      withdateranges: true,
      hide_volume: false,
      padding: 0,
      container_id: `tradingview_${containerId.replace(/:/g, '_')}`
    })

    const widgetContainer = document.createElement('div')
    widgetContainer.className = 'tradingview-widget-container__widget'
    widgetContainer.style.height = '100%'
    widgetContainer.style.width = '100%'
    
    container.current.appendChild(widgetContainer)
    container.current.appendChild(script)

  }, [symbol, theme, language, containerId])

  return (
    <div 
      id={`tradingview_${containerId.replace(/:/g, '_')}`}
      className="tradingview-widget-container" 
      ref={container} 
      style={{ height: height, width: '100%', borderRadius: '0.5rem', overflow: 'hidden' }}
    >
      <div className="tradingview-widget-container__widget"></div>
    </div>
  )
}

export default memo(TradingViewWidget)
